#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简化的主程序
第一步：检测标题
第二步：解析PDF获取DOI
第三步：等待命令
"""

import sys
import os
from pdf_doi_extractor import PDFDOIExtractor
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)


def main():
    """主函数"""
    print("🚀 PDF标题检测和DOI提取系统")
    print("="*60)
    print("第一步：检测标题")
    print("第二步：解析PDF获取DOI")
    print("第三步：等待命令")
    print("="*60)
    
    # 配置参数
    from config import PDF_DIR, MAX_FILES, QWEN_API_KEY, QWEN_API_BASE, TARGET_COMPLETE_COUNT
    pdf_dir = PDF_DIR
    max_files = MAX_FILES
    target_complete_count = TARGET_COMPLETE_COUNT
    
    if not os.path.exists(pdf_dir):
        print(f"❌ PDF目录不存在: {pdf_dir}")
        return
    
    try:
        # 初始化提取器
        print("🔧 初始化PDF DOI提取器...")
        extractor = PDFDOIExtractor(
            pdf_dir, 
            api_key=QWEN_API_KEY,
            api_base=QWEN_API_BASE
        )
        
        # 批量处理
        print(f"\n📚 开始处理PDF文件...")
        print(f"🎯 目标：找到 {target_complete_count} 个包含完整信息（标题、DOI、作者）的数据")
        results = extractor.batch_process(max_files=max_files, target_complete_count=target_complete_count)
        
        # 输出结果汇总
        print(f"\n📊 处理完成！结果汇总:")
        print("="*60)
        
        for i, result in enumerate(results, 1):
            print(f"文件 {i}: {result['file_name']}")
            print(f"  标题: {result['title'] if result['title'] else '未检测到'}")
            print(f"  DOI: {result['doi'] if result['doi'] else '未找到'}")
            print(f"  作者: {result['author'] if result['author'] else '未找到'}")
            print("-" * 40)
        
        # 统计信息
        total_files = len(results)
        title_success = sum(1 for r in results if r['title'])
        doi_success = sum(1 for r in results if r['doi'])
        author_success = sum(1 for r in results if r['author'])
        complete_count = sum(1 for r in results if r['title'] and r['doi'] and r['author'])
        
        print(f"\n📈 统计信息:")
        print(f"   总文件数: {total_files}")
        print(f"   标题提取成功率: {title_success}/{total_files} ({title_success/total_files*100:.1f}%)")
        print(f"   DOI提取成功率: {doi_success}/{total_files} ({doi_success/total_files*100:.1f}%)")
        print(f"   作者提取成功率: {author_success}/{total_files} ({author_success/total_files*100:.1f}%)")
        print(f"   完整信息数量: {complete_count}/{total_files} ({complete_count/total_files*100:.1f}%)")
        
        print(f"\n✅ 第一步和第二步已完成！")
        print("第三步：等待你的命令...")
        
    except Exception as e:
        logger.error(f"程序执行失败: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    main()
